﻿using AutoMapper;
using Common.Enum;
using Entity.ERP.DTO.PurchaseOrder;
using Entity.ERP.Entity;
using Entity.ERP.View.PurchaseOrder;
using Entity.ERP.View.PurchaseOrderItem;
using FrameWork.DataContext;
using FrameWork.DataHelper;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;

namespace Service.ERP
{
    public class PurchaseOrderService
    {
        /**
         * 数据库
         */
        private readonly DataContext _context;

        /**
         * 自动映射
         */
        private readonly IMapper _mapper;

        /**
         * 构造注入
         */
        public PurchaseOrderService(DataContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        /**
         * 获取采购订单列表
         */
        public async Task<RequestResponseModel<PageResult<PurchaseOrderView>>> GetPurchaseOrderList(PurchaseOrderSearchDTO purchaseOrderSearchDTO)
        {
            //筛选
            var query = _context.PurchaseOrderView
                .WhereIF(a => a.Code.Contains(purchaseOrderSearchDTO.Code), !string.IsNullOrEmpty(purchaseOrderSearchDTO.Code))
                .WhereIF(a => a.CardNo.Contains(purchaseOrderSearchDTO.CardNo), !string.IsNullOrEmpty(purchaseOrderSearchDTO.CardNo))
                .WhereIF(a => a.SupplierCode.Contains(purchaseOrderSearchDTO.Supplier) || a.SupplierName.Contains(purchaseOrderSearchDTO.Supplier), !string.IsNullOrEmpty(purchaseOrderSearchDTO.Supplier))
                .WhereIF(a => a.Status == purchaseOrderSearchDTO.Status, purchaseOrderSearchDTO.Status != null)
                .WhereIF(a => a.ExamStatus == purchaseOrderSearchDTO.ExamStatus, purchaseOrderSearchDTO.ExamStatus != null)
                ;

            //返回列表
            var purchaseOrderList = await query
                .Page(purchaseOrderSearchDTO.CurrentPage, purchaseOrderSearchDTO.PageSize)
                .ToListAsync();

            //计算总数
            var pageCount = await query.CountAsync();

            //返回数据
            var pageResult = new PageResult<PurchaseOrderView>(purchaseOrderList, pageCount);
            return RequestResponse.CreateResponse(200, "查询成功", pageResult);
        }

        /**
         * 获取采购订单子单列表
         */
        public async Task<RequestResponseModel<PageResult<PurchaseOrderItemView>>> GetPurchaseOrderItemList(PurchaseOrderItemSearchDTO purchaseOrderItemSearchDTO)
        {
            //筛选
            var query = _context.PurchaseOrderItemView
                .Where(a => a.PurchaseOrderId == purchaseOrderItemSearchDTO.Id)
                ;

            //返回列表
            var purchaseOrderItemList = await query
                .Page(purchaseOrderItemSearchDTO.CurrentPage, purchaseOrderItemSearchDTO.PageSize)
                .ToListAsync();

            //计算总数
            var pageCount = await query.CountAsync();

            //返回数据
            var pageResult = new PageResult<PurchaseOrderItemView>(purchaseOrderItemList, pageCount);
            return RequestResponse.CreateResponse(200, "查询成功", pageResult);
        }

        /**
         * 新增采购订单
         */
        public async Task<RequestResponseModel<string>> AddPurchaseOrder(PurchaseOrderAddDTO purchaseOrderAddDTO)
        {
            //处理主单
            var purchaseOrder = _mapper.Map<PurchaseOrderModel>(purchaseOrderAddDTO);
            purchaseOrder.Id = Guid.NewGuid().ToString();
            purchaseOrder.Status = StateEnum.PurchaseType.待生成;
            purchaseOrder.ExamStatus = StateEnum.ExamStatus.待审核;
            purchaseOrder.CreateTime = DateTime.Now;

            //处理子单数据
            var purchaseOrderItemList = _mapper.Map<List<PurchaseOrderItemModel>>(purchaseOrderAddDTO.Items);
            foreach (var item in purchaseOrderItemList)
            {
                item.Id = Guid.NewGuid().ToString();
                item.PurchaseOrderId = purchaseOrder.Id;
                item.CardNo = purchaseOrder.CardNo;
            }

            //保存数据
            _context.PurchaseOrder.Add(purchaseOrder);
            _context.PurchaseOrderItem.AddRange(purchaseOrderItemList);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "新增成功", purchaseOrder.Id);
        }

        /**
         * 编辑采购订单
         */
        public async Task<RequestResponseModel<string>> PutPurchaseOrder(PurchaseOrderUpdateDTO purchaseOrderUpdateDTO)
        {
            //校验id有效性
            var query = await Valid.ValidId(_context.PurchaseOrder, purchaseOrderUpdateDTO.Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "采购订单id无效", purchaseOrderUpdateDTO.Id);
            }

            //只有待审核的单据才能编辑
            if (query.ExamStatus != StateEnum.ExamStatus.待审核)
            {
                return RequestResponse.CreateResponse(400, "只有待审核的订单才能编辑", purchaseOrderUpdateDTO.Id);
            }

            //处理主单
            var purchaseOrder = _mapper.Map<PurchaseOrderModel>(purchaseOrderUpdateDTO);
            //处理子单
            var purchaseOrderItemList = _mapper.Map<List<PurchaseOrderItemModel>>(purchaseOrderUpdateDTO.Items);

            //修改并保存数据库
            _context.PurchaseOrder.Update(purchaseOrder);
            _context.PurchaseOrderItem.UpdateRange(purchaseOrderItemList);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "更新成功", query.Id);
        }

        /**
         * 删除采购订单
         */
        public async Task<RequestResponseModel<string>> DeletePurchaseOrder(string Id)
        {
            //校验id有效性
            var query = await Valid.ValidId(_context.PurchaseOrder, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "id无效", Id);
            }

            //已审核的单据无法删除
            if (query.Status != StateEnum.PurchaseType.待生成)
            {
                return RequestResponse.CreateResponse(400, "只有待生成的单据才能删除", Id);
            }

            //查找该id下的子单
            var purchaseOrderItemList = _context.PurchaseOrderItem
                .Where(a => a.PurchaseOrderId.Equals(Id));

            //操作数据库并保存
            _context.PurchaseOrder.Remove(query);
            _context.PurchaseOrderItem.RemoveRange(purchaseOrderItemList);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "删除成功", Id);
        }

        /**
         * 审核通过采购订单
         */
        public async Task<RequestResponseModel<string>> PassPurchaseOrder(string Id)
        {
            //校验id
            var query = await Valid.ValidId(_context.PurchaseOrder, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "Id无效", Id);
            }

            //校验状态
            if (query.ExamStatus != StateEnum.ExamStatus.待审核)
            {
                return RequestResponse.CreateResponse(400, "只有待审核的单据才可以审核通过", Id);
            }

            //修改数据
            query.ExamStatus = StateEnum.ExamStatus.审核通过;

            //保存数据库
            _context.PurchaseOrder.Update(query);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "审核通过成功", Id);
        }

        /**
         * 审核不通过采购订单
         */
        public async Task<RequestResponseModel<string>> UnPassPurchaseOrder(string Id)
        {
            //校验id
            var query = await Valid.ValidId(_context.PurchaseOrder, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "Id无效", Id);
            }

            //校验状态
            if (query.ExamStatus != StateEnum.ExamStatus.待审核)
            {
                return RequestResponse.CreateResponse(400, "只有待审核的单据才可以审核不通过", Id);
            }

            //修改数据
            query.ExamStatus = StateEnum.ExamStatus.审核不通过;

            //保存数据库
            _context.PurchaseOrder.Update(query);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "审核不通过成功", Id);
        }

        /**
         * 反审核采购订单
         */
        public async Task<RequestResponseModel<string>> CancelPassPurchaseOrder(string Id)
        {
            //校验id
            var query = await Valid.ValidId(_context.PurchaseOrder, Id);
            if (query == null)
            {
                return RequestResponse.CreateResponse(400, "Id无效", Id);
            }

            //校验状态
            if (query.Status != StateEnum.PurchaseType.待生成)
            {
                return RequestResponse.CreateResponse(400, "只有待生成的单据才可以反审核", Id);
            }

            //修改数据
            query.ExamStatus = StateEnum.ExamStatus.待审核;

            //保存数据库
            _context.PurchaseOrder.Update(query);
            await _context.SaveChangesAsync();
            return RequestResponse.CreateResponse(200, "反审核成功", Id);
        }
    }
}